// defaults
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
                getService(Components.interfaces.nsIPrefBranch);
var fsb = document.getElementById("flickrSideBW");
var authToken = '';
var nsid = '';
var requiresAuth = 0;
var frequency = 300000;
var autofrequency = frequency;
var streamSize = 10;
var photoSize = 't';
var timerID;
var singlephoto = 0;
var stream = 'e';
var baseURL = "http://www.yupoo.com/api/rest/";
var everyoneUrl = baseURL + "?method=yupoo.photos.getRecent&api_key=2e7f6b3f4438c334e110887a0da87aec&per_page=";
//var contactUrl = baseURL + "?method=yupoo.photos.getInterestingList&api_key=2e7f6b3f4438c334e110887a0da87aec&";
var friendsUrl = baseURL + "?method=yupoo.photos.getContactsPhotos&api_key=2e7f6b3f4438c334e110887a0da87aec&just_friends=1&";
var favoritesUrl = baseURL + "?method=yupoo.favorites.getList&api_key=2e7f6b3f4438c334e110887a0da87aec";
var groupUrl = baseURL + "?method=yupoo.groups.pools.getPhotos&api_key=2e7f6b3f4438c334e110887a0da87aec&per_page=";
var groupPhotosUrl = baseURL + "?method=yupoo.groups.pools.getPhotos&api_key=2e7f6b3f4438c334e110887a0da87aec&group_id=";
var yourUrl = baseURL + "?method=yupoo.photos.search&api_key=2e7f6b3f4438c334e110887a0da87aec&";
var interestUrl = baseURL + "?method=yupoo.interestingness.getList&api_key=2e7f6b3f4438c334e110887a0da87aec&extras=owner_name&per_page=";
var runUrl = everyoneUrl;
var url = '';
var key = '2e7f6b3f4438c334e110887a0da87aec';
var sharedSecret = 'esthlxk8zdtnsbsz';
var frob = '';
var signstring = '';

// this is here because of a bug [97283] in the 1.7 branch (firefox 1.0).
// It shouldn't be necessary in 1.8 (firefox 1.1)
// retaining for users of ff 1.0 27/8/2006
function fixScroll(div) {
    var s = div.scrollTop;
    div.childNodes[1].focus();
    div.scrollTop = s;
}
//end



function saveSectionTitle(title) {
    prefs.setCharPref("cn.xpies.yupoofox.sectionTitle", title);
}


function doNext(type,thisPage) {
    thisPage += 1;
    if(type == "search") {
        doSearch(thisPage);  
    }
    if(type == "stream") {
        getRecent(thisPage);
    }
}

function doPrev(type,thisPage) {
    if(thisPage > 1) {
        thisPage -= 1;
    }
    if(type == "search") {
        doSearch(thisPage);  
    }
    if(type == "stream") {
        getRecent(thisPage);
    }
}

function setNextPrev(curPage,totalPages,type) {
    // next
    if(curPage < totalPages) {
        document.getElementById('next_1').setAttribute("class", "initialized");
        document.getElementById('next_1').setAttribute("title", "view older photos");
        document.getElementById('next_1').onclick = function() {
            doNext(type,curPage);
            };
        document.getElementById('next_2').setAttribute("class", "initialized");
        document.getElementById('next_2').setAttribute("title", "view older photos");
        document.getElementById('next_2').onclick = function() {
            doNext(type,curPage);
            };   
    } else {
        document.getElementById('next_1').setAttribute("class", "uninitialized");
        document.getElementById('next_1').setAttribute("title", "");
        document.getElementById('next_1').onclick = function() {};
        document.getElementById('next_2').setAttribute("class", "uninitialized");
        document.getElementById('next_2').setAttribute("title", "");
        document.getElementById('next_2').onclick = function() {}; 
    }
    // prev
    if(curPage > 1) {
        document.getElementById('prev_1').setAttribute("class", "initialized");
        document.getElementById('prev_1').setAttribute("title", "view newer photos");
        document.getElementById('prev_1').onclick = function() {
            doPrev(type,curPage);
            };
        document.getElementById('prev_2').setAttribute("class", "initialized");
        document.getElementById('prev_2').setAttribute("title", "view newer photos");
        document.getElementById('prev_2').onclick = function() {
            doPrev(type,curPage);
            };  
    } else {
        document.getElementById('prev_1').setAttribute("class", "uninitialized");
        document.getElementById('prev_1').setAttribute("title", "");
        document.getElementById('prev_1').onclick = function() {};
        document.getElementById('prev_2').setAttribute("class", "uninitialized");
        document.getElementById('prev_2').setAttribute("title", "");
        document.getElementById('prev_2').onclick = function() {};  
    }
}

function setSectionTitle(title) {
    if(!title) {
        if (prefs.getPrefType("cn.xpies.yupoofox.sectionTitle") == prefs.PREF_STRING){
            title = prefs.getCharPref("cn.xpies.yupoofox.sectionTitle");
        } else {
            title = "yupoofox";
        } 
    }
    var j = document.getElementById('ff_sectionTitle');
    for(var i=j.childNodes.length; i>0; i--) {
            j.removeChild(j.lastChild);
    }
    var title = decodeURI(title);
    var k = document.createTextNode(title);    
    j.appendChild(k);
}


function startFF() {
    getCredentials()
    checkToken();
}

function getCredentials() {
    fillThrob();
    if (prefs.getPrefType("cn.xpies.yupoofox.com.yupoo.token") == prefs.PREF_STRING){
        authToken = prefs.getCharPref("cn.xpies.yupoofox.com.yupoo.token");
    }
    if (prefs.getPrefType("cn.xpies.yupoofox.streamsize") == prefs.PREF_INT){
        streamSize = prefs.getIntPref("cn.xpies.yupoofox.streamsize");
    }
    if (prefs.getPrefType("cn.xpies.yupoofox.stream") == prefs.PREF_STRING) {
        stream = prefs.getCharPref("cn.xpies.yupoofox.stream");
    }
    if (prefs.getPrefType("cn.xpies.yupoofox.thumbsize") == prefs.PREF_STRING){
        photoSize = prefs.getCharPref("cn.xpies.yupoofox.thumbsize");
        if ((photoSize != 't') && (photoSize != 's')) {
            photoSize = 't';
        }
    }
    if (prefs.getPrefType("cn.xpies.yupoofox.nsid") == prefs.PREF_STRING) {
        nsid = prefs.getCharPref("cn.xpies.yupoofox.nsid");
    }
    if (prefs.getPrefType("cn.xpies.yupoofox.singlephoto") == prefs.PREF_INT) {
        singlephoto = prefs.getIntPref("cn.xpies.yupoofox.singlephoto");
    }
}

function checkToken() {
	signstring = "esthlxk8zdtnsbszapi_key" + key + "auth_token" + authToken + "methodyupoo.auth.checkToken";
    signed = MD5(signstring);
    // this checks to see if the token we have needs renewing
    var checkTokenurl = baseURL + "?method=yupoo.auth.checkToken&api_key=" + key + "&auth_token=" + authToken + "&api_sig=" + signed;
    //checkTokenurl = signCall(checkTokenurl);
    fxmlhttp = new XMLHttpRequest();
    fxmlhttp.open("GET",checkTokenurl,true);
    fxmlhttp.onreadystatechange=function() {
        if (fxmlhttp.readyState==4) {
            var stateCheckReturn= fxmlhttp.responseXML.getElementsByTagName("rsp");
            var stateCheck = stateCheckReturn[0].attributes["stat"].value;
            if (stateCheck == 'fail') {
                getFrobAndAuthorise();
            } else {
                fillGroups();
                getRecent();
            }
        }
    }
    try {
    fxmlhttp.send(null);
    } catch(e){}
}

function getFrobAndAuthorise() {
    signed = MD5('esthlxk8zdtnsbszapi_key2e7f6b3f4438c334e110887a0da87aecmethodyupoo.auth.getFrob');
	var base = 'http://www.yupoo.com/api/rest/';
    froburl = base + "?method=yupoo.auth.getFrob&api_key=";
    froburl = froburl + "2e7f6b3f4438c334e110887a0da87aec&api_sig=" + signed;
    fxmlhttp = new XMLHttpRequest();
    fxmlhttp.open("GET",froburl,true);
    fxmlhttp.onreadystatechange=function() {
    if (fxmlhttp.readyState==4) {
        var frobReturn = fxmlhttp.responseXML.getElementsByTagName("frob");
        frob = frobReturn[0].firstChild.nodeValue;
        signstring = 'esthlxk8zdtnsbszapi_key' + key + 'frob' + frob + 'permswrite';
        sig = MD5(signstring);
        loc = 'http://www.yupoo.com/services/auth/?api_key=' + key + "&perms=write&frob=" + frob + "&api_sig=" + sig;
        //opening a new focused tab.
        const kWindowMediatorContractID = "@mozilla.org/appshell/window-mediator;1";
        const kWindowMediatorIID = Components.interfaces.nsIWindowMediator;
        const kWindowMediator = Components.classes[kWindowMediatorContractID].getService(kWindowMediatorIID);
        var browserWindow = kWindowMediator.getMostRecentWindow("navigator:browser");
        var browser = browserWindow.getBrowser();
        var tab = browser.addTab(loc);
        browser.selectedTab = tab;
        setSectionTitle("Authorize");
        var authbox = document.getElementById("auth");
        var i = document.createElement("button");
        i.setAttribute("label","I'm Done!");
        i.setAttribute("onclick", "requestToken();");
        i.setAttribute("tooltiptext", "Click here when you've finished the Yupoo authorization process.");
        i.setAttribute("class", "authButton");
        var j = document.createElement("description");
        j.setAttribute("width","100");
        j.setAttribute("class","authText");
        var k = document.createTextNode("Click the button above when you have completed the Yupoo Authorization process.");
        j.appendChild(k);
        authbox.appendChild(i);
        authbox.appendChild(j);
        }
    }
    try {
	fxmlhttp.send(null);
    } catch(e){}
}

function requestToken() {
    signstring = "esthlxk8zdtnsbszapi_key" + key + "frob" + frob + "methodyupoo.auth.getToken";
    signed = MD5(signstring);
    tokenURL = baseURL + "?method=yupoo.auth.getToken&api_key=" + key + "&frob=" + frob + "&api_sig=" + signed;
    fxmlhttp = new XMLHttpRequest();
    fxmlhttp.open("GET",tokenURL,true);
    fxmlhttp.onreadystatechange=function() {
    if (fxmlhttp.readyState==4) {
        var stateCheckReturn= fxmlhttp.responseXML.getElementsByTagName("rsp");
        var stateCheck = stateCheckReturn[0].attributes["stat"].value;
        if (stateCheck != 'fail') {
          var rtreturn = fxmlhttp.responseXML.getElementsByTagName("token");
          var nsreturn = fxmlhttp.responseXML.getElementsByTagName("user");
          authToken = rtreturn[0].firstChild.nodeValue;
          prefs.setCharPref("cn.xpies.yupoofox.com.yupoo.token", authToken);
          nsid = nsreturn[0].attributes["id"].value;
          prefs.setCharPref("cn.xpies.yupoofox.nsid", nsid);
          clearAuth();
          fillGroups();
          getRecent();
        } else {
            alert('You must complete the authorisation at yupoo.com');
        }
    }
    }
    try {
	fxmlhttp.send(null);
    } catch(e){}
}

function clearStream() {
    var pop = document.getElementById("ff_streambox");
    for(var i=0; i<pop.childNodes.length; i++) {
        var ch = pop.childNodes[i];
        ch.setAttribute("image", "chrome://yupoofox/skin/blank.gif");
    }
}

function setStream(id) {
    try {
    var sel = document.getElementById(id);
    sel.setAttribute("image", "chrome://yupoofox/skin/selected.png");
    } catch(e) {}
}

function signCall(url) {
    var urlChunk = url.split('?');
    var params = urlChunk[1].split('&');
    var pArray = new Array();
    for (var p = 0; p < params.length; p++) {
	var k = params[p].split('=');
	pArray.push(k[0] + k[1]);
    }
    pArray.sort();
    var sigString = 'esthlxk8zdtnsbsz' + pArray.join('');
    var sig = MD5(sigString);
    newUrl = url + '&api_sig=' + sig;
    return newUrl;
}

function fillGroups() {
    var selectBox = document.getElementById("ff_streambox");
    var bset = document.getElementById("bset");
    for(var i=selectBox.childNodes.length - 1; i>=7; i--) {
        selectBox.removeChild(selectBox.childNodes.item(i));
    }
    var fxmlhttp;
    fxmlhttp = new XMLHttpRequest();
    var gurl = baseURL + "?method=yupoo.groups.pools.getGroups&api_key=" + key + "&auth_token=" + authToken;
    var gurl = signCall(gurl);
    fxmlhttp.open("GET",gurl,true);
    fxmlhttp.onreadystatechange=function() {
        if (fxmlhttp.readyState==4) {
            var groups = fxmlhttp.responseXML.getElementsByTagName("group");
            for(var i=0; i<groups.length; i++) {
                var g = null;
                g = document.createElement("menuitem");
                g.setAttribute("id", groups[i].attributes["id"].value);
                g.setAttribute("label", groups[i].attributes["name"].value);
                g.setAttribute("class", "menuitem-iconic");
                if (groups[i].attributes["photos"].value == 0) {
                    g.setAttribute("disabled", "true");
                } else {
                    var groupName = groups[i].attributes["name"].value.replace("'","\\'");
                    var cmd = "fireStream('" + groups[i].attributes["id"].value + "','" + groupName + "');"
                    g.setAttribute("oncommand", cmd);
                }
                if (stream == groups[i].attributes["id"].value) {
                    g.setAttribute("image", "chrome://yupoofox/skin/selected.png");
                }
                selectBox.appendChild(g);
            }
        }
    }
    try {
    fxmlhttp.send(null);
    } catch(e){}
}


function addImage(src, tip, url, id, username, userurl) {
    var aBox = document.getElementById("ffsb");
    var j = "jumpTo('" + url + "',event)";
    var uj = "jumpTo('" + userurl + "',event)";
    
    var outerB = document.createElement("hbox");
    outerB.setAttribute("id", id);
    
    var innerD = document.createElement("box");
    innerD.setAttribute("flex","100%");
    
    outerB.appendChild(innerD);
    
    var iBox = document.createElement("vbox");
    iBox.setAttribute("flex","100%");
    iBox.setAttribute("width","110");
    
    var iBox_innerTop = document.createElement("hbox");
    iBox_innerTop.setAttribute("flex","100%");
    
    iBox.appendChild(iBox_innerTop);
    
    var iBox_innerTopSpacerA = document.createElement("box");
    iBox_innerTopSpacerA.setAttribute("flex","100%");
    
    iBox_innerTop.appendChild(iBox_innerTopSpacerA);
    
    var i = document.createElement("image");
    i.setAttribute("src",src);
    i.setAttribute("tooltiptext", tip);
    i.setAttribute("validate", "never");
    i.setAttribute("onclick", j);
    i.setAttribute("class", "flickrimage");
    i.setAttribute("pid", id);
    if(photoSize == 's') {
        i.setAttribute("width", "75px");
        i.setAttribute("height", "75px");
    }
    if(photoSize == 't') {
        i.setAttribute("style", "max-height:100px;max-width:100px");
    }
    
    if(photoSize == "s") {
        iBox_innerTop.appendChild(i);
    } else {
        var bb = document.createElement("hbox");
        bb.setAttribute("class","innerImage");
        iBox_innerTop.appendChild(bb)
        bb.appendChild(i);
    }
    
    var iBox_innerTopSpacerB = document.createElement("box");
    iBox_innerTopSpacerB.setAttribute("flex","100%");
    
    iBox_innerTop.appendChild(iBox_innerTopSpacerB);
    
    var iBox_innerBot = document.createElement("box");
    
    iBox.appendChild(iBox_innerBot);
    
    
    if (username.length > 0) {
       var BottomPadA = document.createElement("box");
       BottomPadA.setAttribute("flex","100%");
       iBox_innerBot.appendChild(BottomPadA);
    
           var k = document.createElement("label");
           k.setAttribute("value", username);
           k.setAttribute("crop", "end");
           k.setAttribute("class", "ffuserlabel");
           k.setAttribute("onclick", uj);
           k.setAttribute("flex","100%");
           k.setAttribute("width","100");
           iBox_innerBot.appendChild(k);
    
       var BottomPadB = document.createElement("box");
       BottomPadB.setAttribute("flex","100%");
       iBox_innerBot.appendChild(BottomPadB);
    
    }
    
    outerB.appendChild(iBox);
    
    var innerF = document.createElement("box");
    innerF.setAttribute("flex","100%");
    
    outerB.appendChild(innerF);
    
    aBox.appendChild(outerB);

}

function clearAuth() {
    var aBox = document.getElementById("auth");
    for(var i=aBox.childNodes.length; i>0; i--) {
            aBox.removeChild(aBox.lastChild);
    }
}

function clearBox() {
    var aBox = document.getElementById("ffsb");
    for(var i=aBox.childNodes.length; i>0; i--) {
            aBox.removeChild(aBox.lastChild);
    }
}

function clearThrob() {
    var aBox = document.getElementById("throb");
    for(var i=aBox.childNodes.length; i>0; i--) {
            aBox.removeChild(aBox.lastChild);
    }
}

function fillThrob() {
    clearThrob();
    var aBox = document.getElementById("throb");
    var i = document.createElement("image");
    i.setAttribute("src","chrome://yupoofox/skin/throb.gif");
    i.setAttribute("tooltiptext", "please wait...");
    aBox.appendChild(i);
}

function fireStream(newstream, label) {
    thisPage = 1;
    fillThrob();
    prefs.setCharPref("cn.xpies.yupoofox.stream", newstream);
    stream = newstream;
    saveSectionTitle(encodeURI(label));
    setSectionTitle(encodeURI(label));
    clearBox();
    getRecent(thisPage);
}

function getRecent(thisPage) {
    if(!thisPage) {thisPage = 1;}
    fillThrob();
    clearStream();
    setStream(stream);
    if (prefs.getPrefType("cn.xpies.yupoofox.sectionTitle") == prefs.PREF_STRING) {
        setSectionTitle();
    }
    switch(stream) {
            case "e":
                    runUrl = everyoneUrl;
                    requiresAuth = 0;
                    break;
            case "i":
                    runUrl = interestUrl;
                    requiresAuth = 0;
                    break;
            case "c":
                    runUrl = contactUrl + "single_photo=" + singlephoto + "&count=";
                    requiresAuth = 1;
                    break;
            case "f":
                    runUrl = friendsUrl + "perguy=" + singlephoto + "&count=";
                    requiresAuth = 1;
                    break
            case "fv":
                    runUrl = favoritesUrl;
                    requiresAuth = 1;
                    break;
            case "y":
              runUrl = yourUrl + "user_id=" + nsid + "&per_page=";
              requiresAuth = 1;  //setting auth will allow a user to see their private photos
              break;
            default:
                var pr = prefs.getCharPref("cn.xpies.yupoofox.stream");
                runUrl = groupPhotosUrl + pr + "&per_page=";
                requiresAuth = 1;

    }

    var fxmlhttp;
    fxmlhttp = new XMLHttpRequest();
    if (runUrl != favoritesUrl) {
            url = runUrl + streamSize + "&page=" + thisPage;
    } else {
            url = runUrl + "&page=" + thisPage;
    }
    if (requiresAuth == 1) {
            url = url + "&auth_token=" + authToken;
            url = signCall(url);
    }
    fxmlhttp.open("GET",url,true);
    var cb = document.getElementById("ffsb");
    fxmlhttp.onreadystatechange=function() {
            if (fxmlhttp.readyState==4) {
                    try {
                        var photos = fxmlhttp.responseXML.getElementsByTagName("photo");
                    }
                        catch(e){ displayNoConnection(); photos = ''; }
                    try {
                        var err = fxmlhttp.responseXML.getElementsByTagName("err");
                    }
                        catch(e) {err = '';}
                        if (err.length == 1) {
                                displayServiceError(err[0].attributes["msg"].value);
                        }
                    try {
                        var root = fxmlhttp.responseXML.getElementsByTagName("result");
                        var totalPages = parseInt(root[0].attributes["pages"].value);
                        var curPage = parseInt(root[0].attributes["page"].value);
                        setNextPrev(curPage,totalPages,"stream");
                    }
                        catch(e) {
                            // getContactsPhotos is not pageable
                            setNextPrev(0,0,"stream");
                        }
                    if(stream == 'e') {
                        // everyone stream moves to quickly for paging to work
                        setNextPrev(0,0,"stream");
                    }
                    refreshDisplay(photos,1);
            }
    }
    try {
    fxmlhttp.send(null);
    } catch(e){}
}

function refreshDisplay(photos,invokeWait) {
    if (photos.length > 0) {
            var newID = photos[photos.length -1].attributes["id"].value;
            var ffsbox = document.getElementById("ffsb");
            if (ffsbox.childNodes.length > 0) {
                    var currentID = ffsbox.childNodes[ffsbox.childNodes.length -1].getAttribute("pid");
            } else {
                    currentID = 0;
            }

            if (newID != currentID) {

                    clearBox();

                    for(var i=0; i<photos.length; i++) {
                            dc = '';
                            filename = photos[i].attributes["filename"].value;
                            id = photos[i].attributes["id"].value;
                            dir = photos[i].attributes["dir"].value;
                            title = photos[i].attributes["title"].value;
                            owner = photos[i].attributes["owner"].value;
                            host = photos[i].attributes["host"].value;
                            try {
                            username = photos[i].attributes["ownername"].value;
                            } catch(e) {
                                    username = '';
                            }
                            if (username.length == 0) {
                                try {
                                        username = photos[i].attributes["ownername"].value;
                                } catch(e){}
                            }

                            src = 'http://photo' + host + '.yupoo.com/' + dir + '/' + filename + '/thumb/' ;
                            url = 'http://www.yupoo.com/photos/view?id=' + id ;
                            userurl = 'http://'+ username +'.yupoo.com/';
                            addImage(src, title, url, id, username, userurl);
                    }

                    autofrequency = frequency;

            } else {

                    autofrequency = autofrequency + 120000;

            }
            if (invokeWait == 1) {
				if (stream == 'e') {
					wait(3000);
				} else {
					wait(autofrequency);
				}
            }
            clearThrob();
    }
}

function wait(intgr) {
    if (stream != 'fv') {
            window.clearTimeout(timerID);
            timerID = window.setTimeout(startFF, intgr);
    }
}

function displayNoConnection() {
    var aBox = document.getElementById("ffsb");
    var i = document.createElement("label");
    i.setAttribute("value","No Connection!");
    i.setAttribute("tooltiptext", "There may be a problem with your internet connection, or with the Yupoo service.");
    i.setAttribute("style", "padding:4px;");
    i.setAttribute("class", "fferrormessage");
    aBox.appendChild(i);
    clearThrob();
}

function displayServiceError(msg) {
    var aBox = document.getElementById("ffsb");
    var i = document.createElement("label");
    i.setAttribute("value","Error!");
    i.setAttribute("tooltiptext", "The Yupoo service returned an error");
    i.setAttribute("style", "padding:4px;");
    i.setAttribute("class", "fferrormessage");
    aBox.appendChild(i);
    var m = document.createElement("label");
    m.setAttribute("value",msg);
    m.setAttribute("tooltiptext", msg);
    i.setAttribute("style", "padding:4px;");
    m.setAttribute("class", "fferrormessagedetail");
    aBox.appendChild(m);
    clearThrob();
}

function jumpTo(loc,event) {
    const kWindowMediatorContractID = "@mozilla.org/appshell/window-mediator;1";
    const kWindowMediatorIID = Components.interfaces.nsIWindowMediator;
    const kWindowMediator = Components.classes[kWindowMediatorContractID].getService(kWindowMediatorIID);
    var browserWindow = kWindowMediator.getMostRecentWindow("navigator:browser");
    var browser = browserWindow.getBrowser();
    var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
    var pmref = ioService.newURI('http://philmccluskey.com/projects/yupoofox/',null,null);
    if (event.button == 2 || event.button == 1 || event.shiftKey == true || event.altKey == true || event.metaKey == 1) {
        //opening a new tab.
        var tab = browser.addTab(loc,pmref);
    } else {
        browser.loadURI(loc,pmref);
    }
}

function doSearch(thisPage) {
    if(!thisPage) {thisPage = 1;}
    fillThrob();
    var s = document.getElementById("ffsearchfield").value;
    //clear timer if it's running
    try {
       window.clearTimeout(timerID);
    } catch(e) {
        //pass
    }
    var ss = s.replace(/[\s]+/g, ",");
    var searchUrl = baseURL + "?method=yupoo.photos.search&api_key=" + key + "&tags=" + ss + "&per_page=" + streamSize + "&page=" + thisPage;
    var fxmlhttp;
    fxmlhttp = new XMLHttpRequest();
    fxmlhttp.open("GET",searchUrl,true);
    var cb = document.getElementById("ffsb");
    fxmlhttp.onreadystatechange=function() {
        if (fxmlhttp.readyState==4) {
            try {
                var photos = fxmlhttp.responseXML.getElementsByTagName("photo");
            }
                catch(e){ displayNoConnection(); photos = ''; }
            try {
                var err = fxmlhttp.responseXML.getElementsByTagName("err");
            }
                catch(e) {err = '';}
                if (err.length == 1) {
                        displayServiceError(err[0].attributes["msg"].value);
                }
            if (photos.length > 0) {
                var root = fxmlhttp.responseXML.getElementsByTagName("result");
                var results = root[0].attributes["total"].value;
                var totalPages = parseInt(root[0].attributes["pages"].value);
                var curPage = parseInt(root[0].attributes["page"].value);
                var perPage = parseInt(root[0].attributes["perpage"].value);
                setNextPrev(curPage,totalPages,"search");
                var toView = perPage * curPage;
                var fromView = toView - perPage + 1;
                setSectionTitle(fromView + ' to ' + toView + ' of ' + results + ' Results');
                refreshDisplay(photos,0);
            } else {
                setSectionTitle('No Results');
                displaySearchError('');
            }
        }
	}
	try {
	fxmlhttp.send(null);
	} catch(e){}
}

function displaySearchError(msg) {
    clearBox();
    var aBox = document.getElementById("ffsb");
    var m = document.createElement("label");
    m.setAttribute("value",msg);
    m.setAttribute("tooltiptext", msg);
    i.setAttribute("style", "padding:4px;");
    m.setAttribute("class", "fferrormessagedetail");
    aBox.appendChild(m);
    clearThrob();
}

function toggleSearch() {
    if (document.getElementById("yupoofox-search").hidden == true) {
        document.getElementById("yupoofox-search").hidden = false;
    } else {
        document.getElementById("yupoofox-search").hidden = true;
        startFF();
    };
}

function openOptions() {
    window.open('chrome://yupoofox/content/options.xul','options','chrome,centerscreen,dialog');
}

function openAbout() {
        loc = 'http://xpies.cn/yupoofox/';
        //opening a new focused tab.
        const kWindowMediatorContractID = "@mozilla.org/appshell/window-mediator;1";
        const kWindowMediatorIID = Components.interfaces.nsIWindowMediator;
        const kWindowMediator = Components.classes[kWindowMediatorContractID].getService(kWindowMediatorIID);
        var browserWindow = kWindowMediator.getMostRecentWindow("navigator:browser");
        var browser = browserWindow.getBrowser();
        var tab = browser.addTab(loc);
        browser.selectedTab = tab;
}

function logout() {
    prefs.setCharPref("cn.xpies.yupoofox.com.yupoo.token", '');
//    prefs.setCharPref("cn.xpies.yupoofox.authtoken", '');
    prefs.setCharPref("cn.xpies.yupoofox.nsid", '');
    authToken = '';
}

function EncodeUtf8(s1)
  {
      var s = escape(s1);
      var sa = s.split("%");
      var retV ="";
      if(sa[0] != "")
      {
         retV = sa[0];
      }
      for(var i = 1; i < sa.length; i ++)
      {
           if(sa[i].substring(0,1) == "u")
           {
               retV += Hex2Utf8(Str2Hex(sa[i].substring(1,5)));
              
           }
           else retV += "%" + sa[i];
      }
     
      return retV;
  }
  function Str2Hex(s)
  {
      var c = "";
      var n;
      var ss = "0123456789ABCDEF";
      var digS = "";
      for(var i = 0; i < s.length; i ++)
      {
         c = s.charAt(i);
         n = ss.indexOf(c);
         digS += Dec2Dig(eval(n));
          
      }
      //return value;
      return digS;
  }
  function Dec2Dig(n1)
  {
      var s = "";
      var n2 = 0;
      for(var i = 0; i < 4; i++)
      {
         n2 = Math.pow(2,3 - i);
         if(n1 >= n2)
         {
            s += '1';
            n1 = n1 - n2;
          }
         else
          s += '0';
         
      }
      return s;
     
  }
  function Dig2Dec(s)
  {
      var retV = 0;
      if(s.length == 4)
      {
          for(var i = 0; i < 4; i ++)
          {
              retV += eval(s.charAt(i)) * Math.pow(2, 3 - i);
          }
          return retV;
      }
      return -1;
  }
  function Hex2Utf8(s)
  {
     var retS = "";
     var tempS = "";
     var ss = "";
     if(s.length == 16)
     {
         tempS = "1110" + s.substring(0, 4);
         tempS += "10" +  s.substring(4, 10);
         tempS += "10" + s.substring(10,16);
         var sss = "0123456789ABCDEF";
         for(var i = 0; i < 3; i ++)
         {
            retS += "%";
            ss = tempS.substring(i * 8, (eval(i)+1)*8);
           
           
           
            retS += sss.charAt(Dig2Dec(ss.substring(0,4)));
            retS += sss.charAt(Dig2Dec(ss.substring(4,8)));
         }
         return retS;
     }
     return "";
  }